<template>
  <div class="department">
    <!-- 筛选区域 -->
    <div class="filter-area">
      <el-select
          v-model="selectedDeptId"
          placeholder="选择部门"
          style="width: 200px; margin-right: 15px"
          @change="handleDeptChange"
      >
        <el-option label="全部部门" value="" />
        <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
        />
      </el-select>

      <el-input
          v-model="searchKey"
          placeholder="搜索员工姓名"
          prefix-icon="Search"
          style="width: 200px"
          @keyup.enter="handleSearch"
      />
      <el-button type="primary" icon="Search" @click="handleSearch" style="margin-left: 10px">
        搜索
      </el-button>
    </div>

    <!-- 员工列表 -->
    <el-table
        :data="filteredEmployees"
        border
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{ background: '#f8f9fa', color: '#666' }"
    >
      <el-table-column prop="name" label="员工姓名" align="center" width="400" />
      <el-table-column prop="currentDept" label="当前部门" align="center" width="400" />
      <el-table-column prop="position" label="职位" align="center" width="400" />
      <el-table-column prop="entryDate" label="入职日期" align="center" width="400" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
              type="primary"
              icon="Edit"
              @click="openEditDialog(scope.row)"
          >
            调整信息
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
        title="调整部门/职位"
        v-model="editDialogVisible"
        width="500px"
        :lock-scroll='false'
    >
      <el-form
          :model="editForm"
          ref="editFormRef"
          label-width="100px"
          :rules="formRules"
      >
        <el-form-item label="员工姓名" prop="name" disabled>
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="调整后部门" prop="deptId">
          <el-select v-model="editForm.deptId" placeholder="选择部门">
            <el-option
                v-for="dept in deptList"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调整后职位" prop="positionId">
          <el-select v-model="editForm.positionId" placeholder="选择职位">
            <el-option
                v-for="pos in positionList"
                :key="pos.id"
                :label="pos.name"
                :value="pos.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调整原因">
          <el-input
              type="textarea"
              v-model="editForm.reason"
              placeholder="请填写调整原因（可选）"
              :rows=3
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认调整</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';

// 部门列表（从后端获取）
const deptList = ref([]);
// 职位列表（从后端获取）
const positionList = ref([]);
// 所有员工数据（从后端获取）
const employeeList = ref([]);
// 筛选条件：选中的部门ID
const selectedDeptId = ref('');
// 搜索关键词
const searchKey = ref('');
// 编辑对话框显示状态
const editDialogVisible = ref(false);
// 编辑表单引用
const editFormRef = ref(null);

// 编辑表单数据
const editForm = reactive({
  id: '', // 员工ID
  name: '', // 员工姓名（只读）
  deptId: '', // 选中的部门ID
  positionId: '', // 选中的职位ID
  reason: '' // 调整原因
});

// 表单验证规则
const formRules = {
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  positionId: [{ required: true, message: '请选择职位', trigger: 'change' }]
};

// 筛选后的员工列表（根据部门和搜索关键词）
const filteredEmployees = computed(() => {
  return employeeList.value.filter(emp => {
    // 部门筛选
    const deptMatch = !selectedDeptId.value || emp.deptId === selectedDeptId.value;
    // 姓名搜索
    const nameMatch = !searchKey.value || emp.name.includes(searchKey.value);
    return deptMatch && nameMatch;
  });
});

// 页面初始化时加载数据
onMounted(() => {
  fetchDeptList(); // 获取部门列表
  fetchPositionList(); // 获取职位列表
  fetchEmployeeList(); // 获取员工列表
});

// ------------------------- 后端接口预留位置 -------------------------
// 1. 获取部门列表
const fetchDeptList = async () => {
  const loading = ElLoading.service({ text: '加载部门列表中...' });
  try {
    // 实际项目中替换为真实接口
    // const res = await axios.get('/api/department/list');
    // deptList.value = res.data.data;

    // 模拟数据
    deptList.value = [
      { id: 1, name: '研发部' },
      { id: 2, name: '测试部' },
      { id: 3, name: '人事部' },
      { id: 4, name: '市场部' }
    ];
    ElMessage.success('部门列表加载成功');
  } catch (error) {
    ElMessage.error('部门列表加载失败');
    console.error('获取部门列表错误：', error);
  } finally {
    loading.close();
  }
};

// 2. 获取职位列表
const fetchPositionList = async () => {
  const loading = ElLoading.service({ text: '加载职位列表中...' });
  try {
    // 实际项目中替换为真实接口
    // const res = await axios.get('/api/position/list');
    // positionList.value = res.data.data;

    // 模拟数据
    positionList.value = [
      { id: 1, name: '前端工程师', deptId: 1 },
      { id: 2, name: '后端工程师', deptId: 1 },
      { id: 3, name: '测试工程师', deptId: 2 },
      { id: 4, name: '人事专员', deptId: 3 },
      { id: 5, name: '市场经理', deptId: 4 }
    ];
  } catch (error) {
    ElMessage.error('职位列表加载失败');
    console.error('获取职位列表错误：', error);
  } finally {
    loading.close();
  }
};

// 3. 获取员工列表（支持按部门筛选）
const fetchEmployeeList = async (deptId = '') => {
  const loading = ElLoading.service({ text: '加载员工列表中...' });
  try {
    // 实际项目中替换为真实接口
    // const res = await axios.get('/api/employee/list', { params: { deptId } });
    // employeeList.value = res.data.data.map(emp => ({
    //   ...emp,
    //   currentDept: deptList.value.find(d => d.id === emp.deptId)?.name || '未知部门'
    // }));

    // 模拟数据
    employeeList.value = [
      {
        id: 1,
        name: '张三',
        deptId: 1,
        currentDept: '研发部',
        position: '前端工程师',
        positionId: 1,
        entryDate: '2023-01-15'
      },
      {
        id: 2,
        name: '李四',
        deptId: 1,
        currentDept: '研发部',
        position: '后端工程师',
        positionId: 2,
        entryDate: '2023-03-20'
      },
      {
        id: 3,
        name: '王五',
        deptId: 2,
        currentDept: '测试部',
        position: '测试工程师',
        positionId: 3,
        entryDate: '2023-02-10'
      }
    ];
  } catch (error) {
    ElMessage.error('员工列表加载失败');
    console.error('获取员工列表错误：', error);
  } finally {
    loading.close();
  }
};

// 4. 提交员工部门/职位调整
const submitEmployeeAdjust = async (data) => {
  try {
    // 实际项目中替换为真实接口
    // const res = await axios.post('/api/employee/adjust', data);
    // return res.data;

    // 模拟接口成功
    return { code: 200, message: '调整成功' };
  } catch (error) {
    console.error('提交调整失败：', error);
    throw new Error('调整失败，请重试');
  }
};

// ------------------------- 前端交互逻辑 -------------------------
// 部门筛选变化时重新加载员工列表
const handleDeptChange = (deptId) => {
  fetchEmployeeList(deptId);
};

// 搜索员工
const handleSearch = () => {
  // 基于前端筛选（也可改为调用后端接口搜索）
  console.log('搜索关键词：', searchKey.value);
};

// 打开编辑对话框
const openEditDialog = (row) => {
  // 填充表单数据
  editForm.id = row.id;
  editForm.name = row.name;
  editForm.deptId = row.deptId;
  editForm.positionId = row.positionId;
  editForm.reason = '';
  // 显示对话框
  editDialogVisible.value = true;
};

// 提交调整表单
const handleSubmit = async () => {
  // 表单验证
  await editFormRef.value.validate();

  // 准备提交数据
  const submitData = {
    employeeId: editForm.id,
    newDeptId: editForm.deptId,
    newPositionId: editForm.positionId,
    reason: editForm.reason
  };

  try {
    // 调用后端接口提交
    const res = await submitEmployeeAdjust(submitData);
    if (res.code === 200) {
      ElMessage.success(res.message);
      // 关闭对话框并刷新员工列表
      editDialogVisible.value = false;
      fetchEmployeeList(selectedDeptId.value); // 刷新当前筛选的部门员工
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
};
</script>

<style scoped>
.department {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  height: 78vh;
}

.filter-area {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}


.el-table__row:hover > td {
  background-color: #f0f7ff !important;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}
</style>